#include "RobotMemoryCache.h"
#include <QDebug>

RobotMemoryCache::RobotMemoryCache(QObject *parent)
    : QObject(parent)
{
    // 初始化清理定时器
    m_cleanupTimer = new QTimer(this);
    m_cleanupTimer->setInterval(10000); // 每10秒清理一次
    connect(m_cleanupTimer, &QTimer::timeout, this, &RobotMemoryCache::cleanupOfflineRobots);
    m_cleanupTimer->start();
    
    qDebug() << "RobotMemoryCache: 内存状态缓存管理器已初始化";
}

RobotMemoryCache::~RobotMemoryCache()
{
    if (m_cleanupTimer) {
        m_cleanupTimer->stop();
    }
    
    QMutexLocker locker(&m_mutex);
    m_robotStatusMap.clear();
    
    qDebug() << "RobotMemoryCache: 内存状态缓存管理器已销毁";
}

void RobotMemoryCache::updateRobotStatus(const QString &sn, const QVariantMap &data)
{
    QMutexLocker locker(&m_mutex);
    
    RobotStatus &status = m_robotStatusMap[sn];
    status.data = data;
    status.lastUpdate = QDateTime::currentDateTime();
    status.needsArchiving = true;
    
    // 如果包含位置信息，立即发送信号
    if (data.contains("pos_x") && data.contains("pos_y")) {
        QVariantMap locationData;
        locationData["pos_x"] = data["pos_x"];
        locationData["pos_y"] = data["pos_y"];
        if (data.contains("pos_z")) {
            locationData["pos_z"] = data["pos_z"];
        }
        
        // 释放锁后发送信号，避免死锁
        locker.unlock();
        emit robotStatusUpdated(sn, locationData);
        return;
    }
    
    // 释放锁后发送通用状态更新信号
    locker.unlock();
    emit robotStatusUpdated(sn, data);
}

void RobotMemoryCache::updateRobotConnection(const QString &sn, bool online, const QDateTime &lastPing)
{
    QMutexLocker locker(&m_mutex);
    
    RobotStatus &status = m_robotStatusMap[sn];
    bool oldOnline = status.online;
    status.online = online;
    status.lastPing = lastPing.isValid() ? lastPing : QDateTime::currentDateTime();
    
    // 如果在线状态发生变化，发送信号
    if (oldOnline != online) {
        locker.unlock();
        emit robotConnectionChanged(sn, online);
    }
}

QVariantMap RobotMemoryCache::getRobotStatus(const QString &sn) const
{
    QMutexLocker locker(&m_mutex);
    
    auto it = m_robotStatusMap.find(sn);
    if (it != m_robotStatusMap.end()) {
        QVariantMap result = it.value().data;
        result["online"] = it.value().online;
        result["last_update"] = it.value().lastUpdate;
        result["last_ping"] = it.value().lastPing;
        return result;
    }
    
    return QVariantMap();
}

QVariantList RobotMemoryCache::getAllOnlineRobots() const
{
    QMutexLocker locker(&m_mutex);
    
    QVariantList onlineRobots;
    auto it = m_robotStatusMap.constBegin();
    
    while (it != m_robotStatusMap.constEnd()) {
        if (it.value().online) {
            QVariantMap robotInfo;
            robotInfo["sn"] = it.key();
            robotInfo["data"] = it.value().data;
            robotInfo["online"] = true;  // 【修复】明确设置在线状态为true
            robotInfo["last_update"] = it.value().lastUpdate;
            robotInfo["last_ping"] = it.value().lastPing;
            onlineRobots.append(robotInfo);
        }
        ++it;
    }
    
    return onlineRobots;
}

QDateTime RobotMemoryCache::getLastUpdateTime(const QString &sn) const
{
    QMutexLocker locker(&m_mutex);
    
    auto it = m_robotStatusMap.find(sn);
    if (it != m_robotStatusMap.end()) {
        return it.value().lastUpdate;
    }
    
    return QDateTime();
}

bool RobotMemoryCache::isRobotOnline(const QString &sn) const
{
    QMutexLocker locker(&m_mutex);
    
    auto it = m_robotStatusMap.find(sn);
    if (it != m_robotStatusMap.end()) {
        return it.value().online;
    }
    
    return false;
}

void RobotMemoryCache::removeRobot(const QString &sn)
{
    QMutexLocker locker(&m_mutex);
    
    if (m_robotStatusMap.remove(sn) > 0) {
        locker.unlock();
        emit offlineRobotCleaned(sn);
        qDebug() << "RobotMemoryCache: 已清理离线机器人内存数据:" << sn;
    }
}

QVariantList RobotMemoryCache::getRobotsForArchiving() const
{
    QMutexLocker locker(&m_mutex);
    
    QVariantList robotsForArchive;
    QDateTime currentTime = QDateTime::currentDateTime();
    
    auto it = m_robotStatusMap.constBegin();
    while (it != m_robotStatusMap.constEnd()) {
        const RobotStatus &status = it.value();
        
        // 检查是否需要归档：数据需要归档且距离上次归档超过指定时间
        qint64 timeSinceLastArchive = status.lastArchive.isValid() ? 
            status.lastArchive.msecsTo(currentTime) : ARCHIVE_INTERVAL;
        
        if (status.needsArchiving && timeSinceLastArchive >= ARCHIVE_INTERVAL) {
            QVariantMap archiveData;
            archiveData["sn"] = it.key();
            archiveData["data"] = status.data;
            archiveData["last_update"] = status.lastUpdate;
            archiveData["online"] = status.online;
            robotsForArchive.append(archiveData);
        }
        ++it;
    }
    
    return robotsForArchive;
}

void RobotMemoryCache::markAsArchived(const QString &sn)
{
    QMutexLocker locker(&m_mutex);
    
    auto it = m_robotStatusMap.find(sn);
    if (it != m_robotStatusMap.end()) {
        it.value().needsArchiving = false;
        it.value().lastArchive = QDateTime::currentDateTime();
    }
}

int RobotMemoryCache::getRobotCount() const
{
    QMutexLocker locker(&m_mutex);
    return m_robotStatusMap.size();
}

void RobotMemoryCache::cleanupOfflineRobots()
{
    QMutexLocker locker(&m_mutex);
    
    QDateTime currentTime = QDateTime::currentDateTime();
    QList<QString> robotsToRemove;
    
    auto it = m_robotStatusMap.constBegin();
    while (it != m_robotStatusMap.constEnd()) {
        const RobotStatus &status = it.value();
        
        // 检查是否离线超时
        if (!status.online && status.lastUpdate.isValid()) {
            qint64 offlineDuration = status.lastUpdate.msecsTo(currentTime);
            if (offlineDuration > OFFLINE_TIMEOUT) {
                robotsToRemove.append(it.key());
            }
        }
        ++it;
    }
    
    // 移除超时的离线机器人
    for (const QString &sn : robotsToRemove) {
        m_robotStatusMap.remove(sn);
        locker.unlock();
        emit offlineRobotCleaned(sn);
        qDebug() << "RobotMemoryCache: 自动清理离线机器人:" << sn;
        locker.relock();
    }
    
    if (!robotsToRemove.isEmpty()) {
        qDebug() << "RobotMemoryCache: 本次清理" << robotsToRemove.size() << "个离线机器人";
    }
}